package com.candy.candyproduct.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.candy.candyproduct.bean.EsQuestion;
import com.candy.candyproductservice.dto.EsSearchDTO;
import lombok.extern.slf4j.Slf4j;
import org.frameworkset.elasticsearch.ElasticSearchException;
import org.frameworkset.elasticsearch.boot.BBossESStarter;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.frameworkset.elasticsearch.client.ClientUtil;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author suYanLong
 * @date 2022年08月01日 10:38
 */
@Slf4j
@Component
public class EsQuestionService {

    private String index = "cs_question";

    private String mapPath = "es.mapper/EsQuestion.xml";

    @Resource
    BBossESStarter bBossESStarter;

    @PostConstruct
    public void init() {
        ClientInterface clientInterface = bBossESStarter.getConfigRestClient(mapPath);
        try {
            // 判断索引存在不存在
            boolean exist = clientInterface.existIndice(index);
            if (exist) {
                log.info("===>>> es索引 {} 已存在.", index);
                return;
            }

            log.info("===>>> es索引 {} 不存在.", index);
            clientInterface.createIndiceMapping(index, "initIkMaxWord");
            log.info("===>>> es索引 {} init finish", index);

            String getIndex = clientInterface.getIndice(index);
            log.info("create _Mapping clientUtil.getIndice(\"" + index + "\") response:" + getIndex);
        } catch (ElasticSearchException e) {
            log.error("初始化{} 索引异常.", index, e);
            e.printStackTrace();
        }
    }

    // List<String> keywords = Arrays.asList("复盘", "预约单");
    // CsQuestion csQuestion = new CsQuestion(2l, "预约单怎么复盘？", keywords);
    public boolean saveOrUpdate(EsQuestion esQuestion) {
        ClientInterface clientInterface = bBossESStarter.getRestClient();
        String response = clientInterface.addDocument(index, esQuestion, "refresh=true");
        log.debug(response);
        return true;
    }

    /**
     * es调用分词
     */
    @PostConstruct
    public void test() {
        // 创建一个加载配置文件esmapper/sentence_paragrah.xml的rest client接口实例
        Map<String, Object> params = new HashMap<>();
        params.put("searchKeyWords", "小白不懂保险，先了解一下，不是要买，不知道自己的需求，如何成交？");
        ClientInterface clientInterface = bBossESStarter.getConfigRestClient(mapPath);//bboss读取xml
        String analyzeResult = clientInterface.executeHttp(index + "/_analyze", "testHtmlAnalyze", params, ClientUtil.HTTP_POST);
        //分词结果
        log.info("分词结果:{}", analyzeResult);
        // {"tokens":[{"token":"小白","start_offset":0,"end_offset":2,"type":"CN_WORD","position":0},
        // {"token":"不懂","start_offset":2,"end_offset":4,"type":"CN_WORD","position":1},
        // {"token":"保险","start_offset":4,"end_offset":6,"type":"CN_WORD","position":2},
        // {"token":"先","start_offset":7,"end_offset":8,"type":"CN_CHAR","position":3},
        // {"token":"了解","start_offset":8,"end_offset":10,"type":"CN_WORD","position":4},
        // {"token":"一下","start_offset":10,"end_offset":12,"type":"CN_WORD","position":5},
        // {"token":"不是","start_offset":13,"end_offset":15,"type":"CN_WORD","position":6},
        // {"token":"要买","start_offset":15,"end_offset":17,"type":"CN_WORD","position":7},
        // {"token":"不知道","start_offset":18,"end_offset":21,"type":"CN_WORD","position":8},
        // {"token":"自己","start_offset":21,"end_offset":23,"type":"CN_WORD","position":9},
        // {"token":"的","start_offset":23,"end_offset":24,"type":"CN_CHAR","position":10},
        // {"token":"需求","start_offset":24,"end_offset":26,"type":"CN_WORD","position":11},
        // {"token":"如何","start_offset":27,"end_offset":29,"type":"CN_WORD","position":12},
        // {"token":"成交","start_offset":29,"end_offset":31,"type":"CN_WORD","position":13}]}

        JSONObject jsonObject = JSONObject.parseObject(analyzeResult);
        JSONArray tokens = jsonObject.getJSONArray("tokens");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < tokens.size(); i++) {
            if (tokens.getJSONObject(i).getString("token").length() > 1)
                stringBuilder.append(tokens.getJSONObject(i).get("token"));
        }
        log.info(stringBuilder.toString());
    }

    public List<EsQuestion> search(EsSearchDTO esSearchDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("searchKeyWords", esSearchDTO.getSearchKeyWords());
        params.put("size", esSearchDTO.getSize());
        params.put("channelId", esSearchDTO.getChannelId());
        ClientInterface clientInterface = bBossESStarter.getConfigRestClient(mapPath);
        ESDatas<EsQuestion> list =
                clientInterface.searchList(index + "/_search",//demo为索引表，_search为检索操作action
                        "highLightSearch", //esmapper/demo.xml中定义的dsl语句
                        params,//变量参数
                        EsQuestion.class);//返回的文档封装对象类型
        return list != null ? list.getDatas() : null;
    }

}
